import { TemplateFile, templateFile } from "@/api";
import { FormModal } from "@/components";
import { ResultUtil } from "@/util";
import { createAtom, useStore } from "@/util/hooks";
import { Form, Input } from "@arco-design/web-react";
import { useKeyPress } from "ahooks";
import {
  TemplateFileModalStore,
  TemplateFileTree,
  TemplateFileUtil,
  TemplateTreeAtom,
} from "..";
import { useRef } from "react";

export const TemplateFileModalAtom = createAtom<TemplateFileModalStore>({
  open: false,
  type: "add",
  directory: true,
});

export const TemplateFileModal = () => {
  const [form] = Form.useForm();
  const formRef = useRef(null);
  const modalStore = useStore(TemplateFileModalAtom);
  const fileTreeStore = useStore(TemplateTreeAtom);

  async function onConfirm() {
    const values: TemplateFile = await form.validate();
    const { clickedKey, originData } = fileTreeStore.value;
    const { directory } = modalStore.value;
    if (clickedKey) {
      const selectedRecord = TemplateFileUtil.getFileRecord(
        clickedKey,
        originData
      )!;
      values.parentId = clickedKey;
      values.path = selectedRecord.path;
      values.level = selectedRecord.level + 1;
    } else {
      values.parentId = "-1";
      values.level = 0;
    }
    values.directory = directory;

    const res = await templateFile.save(values);
    if (ResultUtil.showError(res)) {
      modalStore.updateStore({
        open: false,
      });
      TemplateFileTree.init(fileTreeStore);
    }
  }

  useKeyPress(
    "enter",
    () => {
      onConfirm();
    },
    { target: formRef }
  );

  const { directory } = modalStore.value;

  return (
    <FormModal
      atom={TemplateFileModalAtom}
      title={directory ? "目录" : "文件"}
      form={form}
      onConfirm={onConfirm}
      autoFocus
    >
      <div ref={formRef}>
        <Form form={form} labelCol={{ span: 5 }}>
          <Form.Item
            label="名称"
            field="fileName"
            requiredSymbol={false}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </div>
    </FormModal>
  );
};
